const http = require("http");
const fs = require("fs");
const path = require("path");
const qs = require("querystring");

const server = http.createServer((req, res) => {
    let {
        method
    } = req;
    let [url, query] = req.url.split("?");
    // console.log(req.url.split("?"));

    let {
        name
    } = qs.parse(query);
    // console.log(name);
    let filePath = path.join(__dirname, "list.json");
    if (method === "GET" && url === "/getList") {
        // res.end('okok')

        let content = fs.readFileSync(filePath, "utf8");
        res.setHeader("content-type", "application/json");
        // console.log(content);    
        // res.end(content);
        let conArr = JSON.parse(content);
        // console.log(conArr);

        let rs = conArr.find(item => item.name === name);
        if (rs) {
            res.end(JSON.stringify(rs));
        } else {
            res.end("unde....find");
        }

    } else if (method === "POST" && url === "/add") {
        console.log('post');

        // var xhr = new XMLHttpRequest();
        // xhr.open('post', 'http://localhost:8080/post');
        // xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
        // xhr.send("name=" + "imissyou".repeat(100000));
        let result = "";
        req.on("data", function (chunck) {
            console.log(chunck);
            result += chunck;
        })


        req.on("end", () => {
            const obj = qs.parse(result);
            // console.log('obj');
            // console.log(obj.name);
            let content = JSON.parse(fs.readFileSync(filePath, "utf8"));
            // console.log(content instanceof Array);
            content.push({
                "name": obj.name
            })
            fs.writeFileSync(filePath, JSON.stringify(content));
        })

        res.statusCode = 200;
        res.end("post ok");
    } else {
        res.end("ok")
    }
})

server.listen(8001, () => {
    console.log('ok');
})